package com.kuaimacode.kframework.component;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kuaimacode.kframework.mybatis.mapper.sms.SmsRecordMapper;
import com.kuaimacode.kframework.mybatis.models.sms.SmsRecord;
import com.kuaimacode.kframework.util.DateUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author qinyong
 * @Title:
 * @Package com.kuaimacode.kframework.api.service
 * @Description: created by IntelliJ IDEA
 * @date 2019-03-14 17:13
 */
@Service
public class SmsRecordService extends ServiceImpl<SmsRecordMapper, SmsRecord> {

    @Value("${sms.valid.code.expired.time}")
    private long expiredTime;

    /**
     * 保存验证码
     * @param mobile
     * @param code
     */
    public void saveRecord(String mobile, String code) {
        SmsRecord smsRecord = new SmsRecord();
        smsRecord.setMobile(mobile);
        smsRecord.setVerify(code);
        smsRecord.setTime(DateUtil.plus(DateUtil.DateEnum.SECONDS, expiredTime));
        baseMapper.insert(smsRecord);
    }

    /**
     * 校验验证码是否正确
     * @param mobile
     * @param verifyCode
     * @return
     */
    public boolean validVerifyCode(String mobile, String verifyCode) {
        /*if ("18800000000".equals(mobile) || "6666".equals(verifyCode)) {
            return true;
        }*/
        if (("13312991307".equals(mobile) && "6666".equals(verifyCode))||("17602180207".equals(mobile) && "6666".equals(verifyCode))) {
            //苹果审核用
            return true;
        }

        QueryWrapper<SmsRecord> qryWrapper = new QueryWrapper<>();
        qryWrapper.eq("mobile", mobile);
        qryWrapper.orderByDesc("time");
        IPage<SmsRecord> page = baseMapper.selectPage(new Page<>(0, 1), qryWrapper);
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return false;
        }

        SmsRecord record = page.getRecords().get(0);
        return record.getVerify().equals(verifyCode) && new Date().before(record.getTime());
    }
}
